<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JVM,锁,">










<meta name="description" content="锁Synchronized需要指定锁定的对象，如果没指定的话，就根据方法是静态方法还是普通方法来锁定对应的Class或者对象。原理是在访问该方法字节码的前后加上 monitorenter 和 monitorexit。 在碰到monitorenter指令的时候，尝试去获取锁，如果线程本身已经持有锁 ，则计数器+1，monitorend的时候计数器-1，当计数器为0的时候释放锁。 阻塞和唤醒线程需要从">
<meta name="keywords" content="JVM,锁">
<meta property="og:type" content="article">
<meta property="og:title" content="锁">
<meta property="og:url" content="https://arrycoder.gitee.io/并发/锁/index.html">
<meta property="og:site_name" content="arry&#39;s blog">
<meta property="og:description" content="锁Synchronized需要指定锁定的对象，如果没指定的话，就根据方法是静态方法还是普通方法来锁定对应的Class或者对象。原理是在访问该方法字节码的前后加上 monitorenter 和 monitorexit。 在碰到monitorenter指令的时候，尝试去获取锁，如果线程本身已经持有锁 ，则计数器+1，monitorend的时候计数器-1，当计数器为0的时候释放锁。 阻塞和唤醒线程需要从">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://arrycoder.gitee.io/blog/并发/锁/lightweight.png">
<meta property="og:updated_time" content="2020-06-16T08:47:21.714Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="锁">
<meta name="twitter:description" content="锁Synchronized需要指定锁定的对象，如果没指定的话，就根据方法是静态方法还是普通方法来锁定对应的Class或者对象。原理是在访问该方法字节码的前后加上 monitorenter 和 monitorexit。 在碰到monitorenter指令的时候，尝试去获取锁，如果线程本身已经持有锁 ，则计数器+1，monitorend的时候计数器-1，当计数器为0的时候释放锁。 阻塞和唤醒线程需要从">
<meta name="twitter:image" content="https://arrycoder.gitee.io/blog/并发/锁/lightweight.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://arrycoder.gitee.io/并发/锁/">





  <title>锁 | arry's blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?97f9adfda8d04eb91dd054a98264d191";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">arry's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://arrycoder.gitee.io/blog/并发/锁/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="arry">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="arry's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">锁</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-05-22T16:13:02+08:00">
                2020-05-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/并发/" itemprop="url" rel="index">
                    <span itemprop="name">并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="锁"><a href="#锁" class="headerlink" title="锁"></a>锁</h1><h2 id="Synchronized"><a href="#Synchronized" class="headerlink" title="Synchronized"></a>Synchronized</h2><p>需要指定锁定的对象，如果没指定的话，就根据方法是静态方法还是普通方法来锁定对应的Class或者对象。原理是在访问该方法字节码的前后加上 monitorenter 和 monitorexit。</p>
<p>在碰到monitorenter指令的时候，尝试去获取锁，如果线程本身已经持有锁 ，则计数器+1，monitorend的时候计数器-1，当计数器为0的时候释放锁。</p>
<p>阻塞和唤醒线程需要从 用户态 转换到 内核态，有可能这个转换时间，比用户的代码执行时间还长。所以synchronized属于一种重量级的操作，JVM本身也加入了一些优化，比如自旋锁、自适应自旋锁，避免线程频繁切换状态。</p>
<h5 id="锁优化"><a href="#锁优化" class="headerlink" title="锁优化"></a>锁优化</h5><ul>
<li><p>自旋锁</p>
<p>线程的挂起和唤醒需要切到内核态中去完成，所以在阻塞的时候会浪费很多资源去完成这些操作。因此在获取锁失败的时候，会让线程空循环一会儿，看看其他线程是否会释放掉锁。因为自旋锁不断做空循环也是会占用执行时间的，所以在自旋一定次数之后还没获取到锁，就按照原本的方式挂起线程并等待唤醒。</p>
<p>同时1.6之后还提供了一个自适应的自旋锁，如果一个线程自旋等待之后获取到了锁，就在下次获取锁的时候加大循环次数，而如果对于一个锁很少获取成功，那么在之后可能就会省去自旋这个步骤，避免浪费处理器资源。</p>
</li>
<li><p>锁消除</p>
<p>经过逃逸分析之后，发现堆上数据不会被其他线程共享，就可以当作是线程私有的数据，无需加同步操作。</p>
</li>
<li><p>锁粗化</p>
<p>在写代码的时候，通常会将锁的粒度写的小一点，这样即使存在锁竞争，也会尽快的释放锁。但是如果存在对同一个对象反复的加锁解锁，即使没有锁竞争也会导致不必要的性能损耗。虚拟机如果检测到这种情况，就会将锁粗化到整个操作序列的外部。</p>
</li>
<li><p>轻量级锁</p>
<p>在虚拟机的对象头里有两部分信息，一部分是对象自身的运行时数据，官方称为<strong>Mark word</strong>，另一个部分用于存储指向方法区对象类型数据的指针，数组对象的话还用于存储数组长度。轻量级锁和偏向锁的实现都是基于Mark Word。</p>
<p>对于32位虚拟机来说，一个无锁对象25位用于存储hashCode，4位存储gc年龄，1位存储偏向锁，剩下两位用来存储锁标志。虚拟机为了节省空间，根据锁标志位的不同，mark word的值也不相同。</p>
</li>
</ul>
<table>
<thead>
<tr>
<th align="center">biased_lock（偏向锁标记）</th>
<th align="center">lock（锁标志）</th>
<th align="center">状态</th>
</tr>
</thead>
<tbody><tr>
<td align="center">0</td>
<td align="center">01</td>
<td align="center">无锁</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center">01</td>
<td align="center">偏向锁</td>
</tr>
<tr>
<td align="center">0</td>
<td align="center">00</td>
<td align="center">轻量级锁</td>
</tr>
<tr>
<td align="center">0</td>
<td align="center">10</td>
<td align="center">重量级锁</td>
</tr>
<tr>
<td align="center">0</td>
<td align="center">11</td>
<td align="center">GC标记</td>
</tr>
</tbody></table>
<p>当一个线程需要对一个对象进行加锁的时候会在栈帧上开辟一块锁记录（Lock Record）的空间，用来存储对象的mark word的拷贝，然后通过CAS将对象头更新为当前线程的指针，并将锁记录更新为00，如果CAS更新失败，再判断对象的指针是否指向自己，如果没指向说明存在着锁竞争，需要膨胀为重量级锁，后面再获取锁的线程都需要进入阻塞状态。</p>
<p><img src="/blog/并发/锁/lightweight.png" alt="轻量级锁膨胀过程"></p>
<ul>
<li><p>偏向锁</p>
<p>偏向锁的目的是为了消除无竞争状态下的同步操作。线程在获取锁的时候，会判断当前对象的mark word里是否有当前线程的id，如果有的话，直接拿来用，省去了CAS的操作。而当另外一个线程尝试获取锁的时候，就会根据当前对象的锁状态来恢复成无锁状态或者升级成轻量级锁。</p>
</li>
</ul>
<p>附上32位虚拟机对象头在不同阶段的结构</p>
<p><strong><em>biased_lock</em></strong>：对象是否启用偏向锁标记，只占1个二进制位。为1时表示对象启用偏向锁，为0时表示对象没有偏向锁。<br> <strong><em>age</em></strong>：4位的Java对象年龄。<br> <strong><em>identity_hashcode</em></strong>：25位的对象标识Hash码，采用延迟加载技术。调用方法<code>System.identityHashCode()</code>计算，并会将结果写到该对象头中。当对象被锁定时，该值会移动到管程Monitor中。<br> <strong><em>thread</em></strong>：持有偏向锁的线程ID。<br> <strong><em>epoch</em></strong>：偏向时间戳。<br> <strong><em>ptr_to_lock_record</em></strong>：指向栈中锁记录的指针。<br> <strong><em>ptr_to_heavyweight_monitor</em></strong>：指向管程Monitor的指针</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">|-------------------------------------------------------|--------------------|</span><br><span class="line">|                  <span class="function">Mark <span class="title">Word</span> <span class="params">(<span class="number">32</span> bits)</span>                  |       State        |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br><span class="line"><span class="function">| identity_hashcode:25 | age:4 | biased_lock:1 | lock:2 |       Normal       |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br><span class="line"><span class="function">|  thread:23 | epoch:2 | age:4 | biased_lock:1 | lock:2 |       Biased       |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br><span class="line"><span class="function">|               ptr_to_lock_record:30          | lock:2 | Lightweight Locked |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br><span class="line"><span class="function">|               ptr_to_heavyweight_monitor:30  | lock:2 | Heavyweight Locked |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br><span class="line"><span class="function">|                                              | lock:2 |    Marked <span class="keyword">for</span> GC   |</span></span><br><span class="line"><span class="function">|-------------------------------------------------------|--------------------|</span></span><br></pre></td></tr></table></figure>

<h2 id="ReentrantLock"><a href="#ReentrantLock" class="headerlink" title="ReentrantLock"></a>ReentrantLock</h2><p>相对于synchronized，ReentrantLock额外提供了 <strong>可中断等待</strong>，<strong>可实现公平锁</strong>，<strong>锁绑定多个条件</strong>三个功能</p>
<ul>
<li><p>可中断等待</p>
<p>内置锁synchronized阻塞的时候是无法中断的，ReentrantLock则提供了<strong><em>lockInterruptibly</em></strong>方法，在等待锁的时候如果收到了interrupt请求，则会中断阻塞状态，抛出异常。除此之外还提供了<strong><em>tryLock</em></strong>方法，在超时时间过后就直接放弃获取锁。</p>
</li>
<li><p>公平锁和非公平锁</p>
<p>多个线程竞争锁的时候，如果按获取锁的位置排队，就是公平锁。非公平锁会先尝试插队，插队失败了再获取锁。ReentrantLock提供了公平锁和非公平锁两种实现，而synchronized关键字只支持非公平锁。</p>
</li>
<li><p>锁绑定多个条件</p>
<p>ReentrantLock使用以下方法，新建多个conditionList</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Condition condition1 = lock.newCondition();</span><br><span class="line">Condition condition2 = lock.newCondition();</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="AQS"><a href="#AQS" class="headerlink" title="AQS"></a>AQS</h3><p>使用双向链表来完成资源获取的排队工作，通过CAS对state值的修改来确认锁的获取。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JVM/" rel="tag"># JVM</a>
          
            <a href="/blog/tags/锁/" rel="tag"># 锁</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/jvm/类加载过程/" rel="next" title="类加载过程">
                <i class="fa fa-chevron-left"></i> 类加载过程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/并发/内存模型/" rel="prev" title="JVM内存模型">
                JVM内存模型 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/uploads/avatar.jpg" alt="arry">
            
              <p class="site-author-name" itemprop="name">arry</p>
              <p class="site-description motion-element" itemprop="description">Java源码/设计模式/个人记录</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#锁"><span class="nav-number">1.</span> <span class="nav-text">锁</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Synchronized"><span class="nav-number">1.1.</span> <span class="nav-text">Synchronized</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#锁优化"><span class="nav-number">1.1.0.0.1.</span> <span class="nav-text">锁优化</span></a></li></ol></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#ReentrantLock"><span class="nav-number">1.2.</span> <span class="nav-text">ReentrantLock</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#AQS"><span class="nav-number">1.2.1.</span> <span class="nav-text">AQS</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">arry</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
